package solver

import (
	"drawgrid/figure"
	"encoding/json"
	"fmt"
	"log"
	"os"
)

func (g *Grid) DrawGrid(fileName string) {

	f := figure.NewFigure(500)

	for rowNum, row := range g.rows {
		for colNum, cell := range row.cells {
			if g.givens[rowNum][colNum] != 0 {
				f.DrawGiven(rowNum, colNum, cell.value)
				continue
			}
			if cell.value != 0 {
				f.DrawValue(rowNum, colNum, cell.value)
			} else {
				f.DrawCands(rowNum, colNum, cell.cands.GetList())
			}
		}
	}
	f.DrawFrame()
	f.Save(fileName)
}

type DrawCell struct {
	Given int
	Value int
	Cands []int
}

type ColorCell struct {
	Row   int
	Col   int
	Cands []int
	Color string
}

type BackgroundCell struct {
	Row   int
	Col   int
	Color string
}

type GridLayout struct {
	DrawCells       []DrawCell
	ColorCells      []ColorCell
	BackgroundCells []BackgroundCell
}

func (l *GridLayout) DrawGrid(fileName string) {
	f := figure.NewFigure(500)

	for _, cell := range l.BackgroundCells {
		f.DrawSquare(cell.Row, cell.Col, cell.Color)
	}

	for _, cell := range l.ColorCells {
		f.DrawMarks(cell.Row, cell.Col, cell.Cands, cell.Color)
	}

	for i, cell := range l.DrawCells {
		rowNum := i / 9
		colNum := i % 9
		if cell.Given != 0 {
			f.DrawGiven(rowNum, colNum, cell.Given)
		} else if cell.Value != 0 {
			f.DrawValue(rowNum, colNum, cell.Value)
		} else {
			f.DrawCands(rowNum, colNum, cell.Cands)
		}
	}

	f.DrawFrame()
	f.Save(fileName)

}
func (g *Grid) WriteDrawJson(fileName string) []byte {
	drawCells := make([]DrawCell, 81)
	for i := range 9 {
		for j := range 9 {
			drawCells[i*9+j].Given = g.givens[i][j]
			drawCells[i*9+j].Value = g.cells[i][j].value
			drawCells[i*9+j].Cands = g.cells[i][j].cands.GetList()
		}
	}
	layout := GridLayout{}
	layout.DrawCells = drawCells

	//green1 := ColorCell{0, 3, []int{1, 7}, "green"}
	//green2 := ColorCell{4, 3, []int{1, 7}, "green"}
	//layout.ColorCells = []ColorCell{green1, green2}

	b, err := json.MarshalIndent(layout, "", "    ")
	if err != nil {
		fmt.Println("error:", err)
		b = []byte{}
	}
	err = os.WriteFile(fileName, b, 0666)
	if err != nil {
		log.Fatal(err)
	}
	//os.Stdout.Write(b)
	return b
}

func ReadDrawJson(b []byte) GridLayout {
	var layout GridLayout

	err := json.Unmarshal(b, &layout)
	if err != nil {
		fmt.Println("error:", err)
	}
	return layout
}

/*
{
  "DrawCells": [
    {
      "Given": 0,
      "Value": 0,
      "Cands": [
        3,
        4
      ]
    },
    {
      "Given": 0,
      "Value": 0,
      "Cands": [
        3,
        4
      ]
    },
	...
  ],
  "ColorCells": [
    {
      "Row": 1,
      "Col": 1,
      "Cands": [
        1,
        2,
        3
      ],
      "Color": "red"
    },
    {
      "Row": 3,
      "Col": 3,
      "Cands": [
        0,
        2
      ],
      "Color": "green"
    }
	...
  ]

*/
